package com.kanshu.ksgb.fastread.doudou.module.home.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.barlibrary.ImmersionBar;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.MessageBean;
import com.kanshu.ksgb.fastread.doudou.common.business.dialog.CommonDialog;
import com.kanshu.ksgb.fastread.doudou.common.business.event.ShelfEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.interfaces.ICancelRefreshing;
import com.kanshu.ksgb.fastread.doudou.common.business.interfaces.IDisposeMessage;
import com.kanshu.ksgb.fastread.doudou.common.business.interfaces.IMainHomeInterface;
import com.kanshu.ksgb.fastread.doudou.common.business.interfaces.ISwitchTab;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.common.business.routerservice.ActivateService;
import com.kanshu.ksgb.fastread.doudou.common.business.routerservice.BookBussinessService;
import com.kanshu.ksgb.fastread.doudou.common.business.routerservice.ConfigService;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.PushUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.kanshu.ksgb.fastread.doudou.common.hotfix.PatchUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.versioncheck.VersionUpdateManager;
import com.kanshu.ksgb.fastread.doudou.common.view.CustomDialog;
import com.kanshu.ksgb.fastread.doudou.common.view.tablayout.TabEntity;
import com.llew.huawei.verifier.LoadedApkHuaWei;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.drakeet.support.toast.ToastCompat;
/**
 * Created by wcy on 2017\6\13 0013
 */
@Route(path = ARouterConfig.HOME_PAGE)
public class AppMainActivity extends BaseActivity implements IDisposeMessage, VersionUpdateManager.IVersionUpdate, IMainHomeInterface {
    public static final String EXTRA_TAB_INDEX = "tab_index";
    public static final String EXTRA_SUB_TAB_INDEX = "sub_tab_index";
    @BindView(R.id.rg_tab)
    LinearLayout mRgTab;
    @BindView(R.id.tv_make_money)
    TextView mMakeMoney;
    @BindView(R.id.person_red_point)
    ImageView mPersonRedPoint;
    private int mCurTabIndex = ARouterConfig.HomePageParams.TAB_SHELF;
    private long mExitTime = 0;
    private Toast mToast;
    private boolean mEditable;
    private SparseArray<TabEntity> mTabArray = new SparseArray<>();
    private int mSubTabIndex = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();
        checkVersion();
        parseIntent();
        initData();
    }

    private void initData() {
        // 微信补丁获取
        PatchUtils.checkPatch();
        // 下载服务开启(通过serviceloader方式)
        ARouter.getInstance().navigation(ActivateService.class).activateService();
        // 初始化拉取配置
        ARouter.getInstance().navigation(ConfigService.class).initConfig();
        // oppo手机 finalizeTimedOut问题修复
        Utils.finalizeTimedOut();
        // 解决在HuaWei手机出现Register too many Broadcast Receivers的crash
        LoadedApkHuaWei.hookHuaWeiVerifier(this.getApplication());
        // 给极光推送打tag
        PushUtils.setAliasTags(Xutils.getContext());
    }

    /**
     * 检查版本更新
     */
    private void checkVersion() {
        VersionUpdateManager.getInstance().setUpdateOnClickListener(this);
        VersionUpdateManager.getInstance().checkVersion(this, false);
    }
    @Override
    protected void initStatusbar() {
        // 半透明A
        try {
            ImmersionBar.with(this).statusBarColor(R.color.color_status_color).init();
            int statusBarHeight = DisplayUtils.getStatusBarHeight(this);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mTitle.getLayoutParams();
            params.topMargin = statusBarHeight;
            mTitle.setLayoutParams(params);
        } catch (Exception e) {
            super.initStatusbar();
            mImmersionBar.keyboardEnable(false);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    private void parseIntent() {
        String tab = getIntent().getStringExtra(EXTRA_TAB_INDEX);
        String subTab = getIntent().getStringExtra(EXTRA_SUB_TAB_INDEX);
        int tabIndex = 0;
        if (!TextUtils.isEmpty(tab)) {
            tabIndex = Integer.parseInt(tab);
        }
        if (!TextUtils.isEmpty(subTab)) {
            mSubTabIndex = Integer.parseInt(subTab);
        }
        switchTab(tabIndex);
    }

    private void initView() {
        goneTitlebar();
        mTabArray.put(ARouterConfig.HomePageParams.TAB_SHELF, new TabEntity(R.id.rb_shelf, getString(R.string.shelf)));
        mTabArray.put(ARouterConfig.HomePageParams.TAB_BOOK_CITY, new TabEntity(R.id.rb_book_city, getString(R.string.book_city)));
        mTabArray.put(ARouterConfig.HomePageParams.TAB_MAKE_MONEY, new TabEntity(0, getString(R.string.make_money)));
        mTabArray.put(ARouterConfig.HomePageParams.TAB_FIND, new TabEntity(R.id.rb_find, getString(R.string.find)));
        mTabArray.put(ARouterConfig.HomePageParams.TAB_PERSON, new TabEntity(R.id.rb_person, getString(R.string.person)));
        mToast = ToastCompat.makeText(Xutils.getContext(), "再按一次退出" + getString(R.string.app_name), Toast.LENGTH_SHORT);
        if (!MMKVDefaultManager.getInstance().isEnableMakeMoneyModule()) {
            mMakeMoney.setText("");
        }
    }


    /**
     * 根据tabIndex 跳转Fragment
     */
    private void showFragment(int tabIndex) {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(mTabArray.get(tabIndex).getText());
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        @SuppressLint("RestrictedApi") List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (!Utils.isEmptyList(fragments)) {
            for (Fragment item : fragments) {
                if (item != null && item.isAdded()) {
                    if (item instanceof ICancelRefreshing) {
                        ((ICancelRefreshing) item).cancel();
                    }
                    transaction.hide(item);
                }
            }
        }
        mCurTabIndex = tabIndex;
        if (fragment != null && fragment.isAdded()) {
            if (fragment instanceof ISwitchTab) {
                ((ISwitchTab) fragment).switchTab(mSubTabIndex);
            }
            transaction.show(fragment);
            mSubTabIndex = -1;
        } else {
            if (tabIndex == ARouterConfig.HomePageParams.TAB_SHELF) {
                boolean newPage = getResources().getBoolean(R.bool.shelf_new_page);
                fragment = (Fragment) ARouter.getInstance().build(newPage ? ARouterConfig.HOME_PAGE_NEW_SHELF : ARouterConfig.HOME_PAGE_SHELF).navigation();
            } else if (tabIndex == ARouterConfig.HomePageParams.TAB_BOOK_CITY) {
                fragment = (Fragment) ARouter.getInstance().build(ARouterConfig.HOME_PAGE_BOOK_CITY).withInt("sub_tab_index", mSubTabIndex).navigation();
            } else if (tabIndex == ARouterConfig.HomePageParams.TAB_FIND) {
                fragment = (Fragment) ARouter.getInstance().build(ARouterConfig.HOME_PAGE_FIND).navigation();
            } else if (tabIndex == ARouterConfig.HomePageParams.TAB_PERSON) {
                fragment = (Fragment) ARouter.getInstance().build(ARouterConfig.HOME_PAGE_PERSONCENTER).navigation();
            } else if (tabIndex == ARouterConfig.HomePageParams.TAB_MAKE_MONEY) {
                mSubTabIndex = 1;
                fragment = (Fragment) ARouter.getInstance().build(ARouterConfig.HOME_PAGE_MAKE_MONEY).withInt("sub_tab_index", mSubTabIndex).navigation();
                mSubTabIndex = -1;
            }
            transaction.add(R.id.main_fragment, fragment, mTabArray.get(tabIndex).getText());
        }
        transaction.commitAllowingStateLoss();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (mEditable && mCurTabIndex == ARouterConfig.HomePageParams.TAB_SHELF) {
                EventBus.getDefault().post(new ShelfEvent(ShelfEvent.CANCEL_ALL));
                return true;
            }
            if (mCurTabIndex != ARouterConfig.HomePageParams.TAB_SHELF) {
                switchTab(ARouterConfig.HomePageParams.TAB_SHELF);
                return true;
            }
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                mToast.setText("再按一次退出" + getString(R.string.app_name));
                mExitTime = System.currentTimeMillis();
                mToast.show();
                return true;
            }
            if (!MMKVUserManager.getInstance().isUserLogin()) {
                CommonDialog.show(this, "您的账号还未登录，处于高危状态！请立即绑定手机号，提升账号安全防止阅读记录等数据遗失！", new CustomDialog.Callback() {
                    @Override
                    public void onSure(Dialog dialog) {
                        ARouterUtils.toActivity(ARouterConfig.PERSONAL_LOGIN_IN, "phone", "");
                        dialog.dismiss();
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        dialog.dismiss();
                        AppMainActivity.this.finish();
                    }
                }).setSureText("马上登录").setCancelText("残忍退出");
                return true;
            }
        }
        mToast.cancel();
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        Utils.fixInputMethodManagerLeak(this);
        ImmersionBar.with(this).destroy();
        super.onDestroy();
        // 阅读器清理动作
        ARouter.getInstance().navigation(BookBussinessService.class).clearReference();
        System.gc();
    }

    @Override
    @SuppressLint("RestrictedApi")
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        parseIntent();
    }
    /**
     * 切换tab
     * 根据 tabIndex 切换
     */
    public void switchTab(int tabIndex) {
        if (tabIndex == ARouterConfig.HomePageParams.TAB_MAKE_MONEY) {
            if (!MMKVUserManager.getInstance().isUserLogin()) {
                ARouterUtils.toActivity(ARouterConfig.PERSONAL_LOGIN_IN, "phone", "");
                return;
            }
        }
        for (int i = 0; i < mRgTab.getChildCount(); i++) {
            mRgTab.getChildAt(i).setSelected(i == tabIndex);
        }
        if (mCurTabIndex != tabIndex) {
            if (tabIndex == ARouterConfig.HomePageParams.TAB_SHELF) {
                AdPresenter.Companion.pvuvStatics(R.string.SJ);
            } else if (tabIndex == ARouterConfig.HomePageParams.TAB_BOOK_CITY) {
                AdPresenter.Companion.pvuvStatics(R.string.SC);
            } else if (tabIndex == ARouterConfig.HomePageParams.TAB_FIND) {
                AdPresenter.Companion.pvuvStatics(R.string.FX);
            } else if (tabIndex == ARouterConfig.HomePageParams.TAB_PERSON) {
                AdPresenter.Companion.pvuvStatics(R.string.WD);
            } else if (tabIndex == ARouterConfig.HomePageParams.TAB_MAKE_MONEY) {
                AdPresenter.Companion.pvuvStatics(R.string.ZQ);
            }
        }
        showFragment(tabIndex);
    }
    @Override
    public void diposeMessage(MessageBean bean) {
        // 打红点
    }


    @Override
    public boolean isSupportSwipeBack() {
        return false;
    }

    @OnClick({R.id.rb_shelf, R.id.rb_book_city, R.id.rb_find, R.id.rb_person_parent, R.id.rg_tab, R.id.tv_make_money})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rb_shelf:
                switchTab(ARouterConfig.HomePageParams.TAB_SHELF);
                break;
            case R.id.rb_book_city:
                switchTab(ARouterConfig.HomePageParams.TAB_BOOK_CITY);
                break;
            case R.id.rb_find:
                switchTab(ARouterConfig.HomePageParams.TAB_FIND);
                break;
            case R.id.rb_person_parent:
                switchTab(ARouterConfig.HomePageParams.TAB_PERSON);
                break;
            case R.id.rg_tab:
                //switchTab(TAB_MAKE_MONEY);
                break;
            case R.id.tv_make_money:
                if (MMKVDefaultManager.getInstance().isEnableMakeMoneyModule()) {
                    switchTab(ARouterConfig.HomePageParams.TAB_MAKE_MONEY);
                }
                break;
        }
    }

    @Override
    public void onCallBack(boolean isUpdate) {
        StorageUtils.setPreference(this, Constants.SP_NAME, "version_update" + UserUtils.getUserId(), isUpdate);
        setRedPoint();
    }

    @Override
    protected String getSpecifyTag() {
        return ARouterConfig.PageTagParams.HOME_PAGE;
    }


    @Override
    public void setEditable(boolean editable) {
        mEditable = editable;
    }

    @Override
    public void setRedPoint() {
        boolean signedToday = StorageUtils.getPreference(getActivity(), Constants.SP_NAME, "signed_today_" + UserUtils.getUserId(), false);
        boolean versionUpdate = StorageUtils.getPreference(getActivity(), Constants.SP_NAME, "version_update" + UserUtils.getUserId(), false);
        boolean isReadFeedback = StorageUtils.getPreference(getActivity(), Constants.SP_NAME, "is_read_feedback_" + UserUtils.getUserId(), false);
        if (signedToday || versionUpdate || isReadFeedback) {
            DisplayUtils.visible(mPersonRedPoint);
        } else {
            DisplayUtils.gone(mPersonRedPoint);
        }
    }
}
